<template>
  <div class="sjzcgl">
    <a-tabs v-model="tabsValue" @change="tabsValueChange">
      <a-tab-pane v-for="(item) in dataStructureList" :key="item.tableId"
       :tab="`${item.type==1?'主':'附'}-${item.tableCnName}`"></a-tab-pane>
    </a-tabs>
    <a-table style="margin-bottom: 20px;" bordered :columns="dataStructureColumns" :scroll="{y: 300}"
    :data-source="dataStructureData" :pagination="false">
      <span slot="action" slot-scope="text, record">
        <div class="dataStructureDragBtn" :draggable="true"
         @dragstart="handledragstart(record, $event)">拖拽</div>
      </span>
    </a-table>
    <assetStatement
      :dataSource="assetStatementDataSource"
      @DropHandler="DropHandler('assetStatementDataSource')"
      @dropItemHandler="dropItemHandler"
      @Delete="(id, idx) => handleDeleteRow('assetStatementDataSource', id, idx)"
    />
    <div class="contentCBtnBox">
      <div class="contentCBtn contentCShowBtn" @click="backModel()">取消</div>
      <div class="contentCBtn contentCSaveBtn" @click="saveData()">保存</div>
    </div>
  </div>
</template>

<script>
import { getAction, postAction } from '@/api/manage'
import assetStatement from './components/assetStatement.vue'
export default {
  components: { assetStatement },
  data() {
    return {
      modelId: null,
      tabsValue: null,
      tempdata: null,
      assetStatementDataSource: [],
      dataStructureList: [],
      dataStructureColumns: [
        {
          title: '序号',
          dataIndex: '序号',
          width: 70,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '表名',
          dataIndex: 'cnName'
        },
        {
          title: '字段名',
          dataIndex: 'enName'
        },
        { title: '操作', dataIndex: 'action', align: 'center', width: 80, scopedSlots: { customRender: 'action' }, }
      ],
      dataStructureData: [],
      url: {
        // 自定义模型-保存数据结构查询
        saveDataStructure: '/sjmx2/modelTemplateCollectConfig/saveDataStructure',
        // 自定义模型-数据结构查询配置
        queryDataStructureConfig: '/sjmx2/modelTemplateCollectConfig/queryDataStructureConfig',
        // 自定义模型-数据结构查询
        queryDataStructure: '/sjmx2/modelTemplateCollectConfig/queryDataStructure',
      },
    }
  },
  created() {
    this.modelId = this.$route.query.modelId;
    this.queryDataStructure();
    this.queryDataStructureConfig();
  },
  methods: {
    // 拖拽---逻辑
    handledragstart(e, el) {
      console.log('树节点 拖拽开始')
      // 中间存储变量
      this.tempdata = { 
        id: e.id, 
        cnName: e.cnName, 
        enName: e.enName, 
        sourceTableName: e.sourceTableName,
        sourceTableCnName: this.dataStructureList.find(item=>item.tableId == this.tabsValue).tableCnName,
      }
      el.dataTransfer.effectAllowed = 'move';
    },
    handleDeleteRow(targetData, id, idx) {
      const dataSource = [...this[targetData]]
      // this[targetData] = dataSource.filter(item => item.id !== id)
      this[targetData] = dataSource.filter((item, index) => index !== idx)
    },
    dropItemHandler(type, idx) {
      if(type == 'relateLinkCnField') {
        let { relateLinkField, relateLinkCnField } = this.assetStatementDataSource[idx];
        if(this.tempdata.sourceTableName != this.assetStatementDataSource[idx].relateTableName) {
          this.$message.error('不可选择多表数据！');
          return
        }
        let sourceTableName = relateLinkField ? relateLinkField.split(',') : [];
        if(sourceTableName.includes(this.tempdata.enName)) {
          this.$message.error('该数据字段已选择');
          return
        }
        sourceTableName.push(this.tempdata.enName);
        let sourceTableCnName = relateLinkCnField ? relateLinkCnField.split(',') : [];
        sourceTableCnName.push(this.tempdata.cnName);
        this.$set(this.assetStatementDataSource[idx], 'relateLinkField', sourceTableName.join(','));
        this.$set(this.assetStatementDataSource[idx], 'relateLinkCnField', sourceTableCnName.join(','));
      }else if(type == 'attachTableCnName' || type == 'attachLinkCnField') {
        let { attachLinkField, attachLinkCnField } = this.assetStatementDataSource[idx];
        if(!this.assetStatementDataSource[idx].attachLinkFieId) {
          this.$set(this.assetStatementDataSource[idx], 'attachTableName', this.tempdata.sourceTableName);
          this.$set(this.assetStatementDataSource[idx], 'attachTableCnName', this.tempdata.sourceTableCnName);
        }else if(this.tempdata.sourceTableName != this.assetStatementDataSource[idx].attachLinkFieId) {
          this.$message.error('不可选择多表数据！');
          return
        }
        let attachFieldCnName = attachLinkField ? attachLinkField.split(',') : [];
        if(attachFieldCnName.includes(this.tempdata.enName)) {
          this.$message.error('该数据字段已选择');
          return
        }
        attachFieldCnName.push(this.tempdata.enName);
        let attachLinkFieCnName = attachLinkCnField ? attachLinkCnField.split(',') : [];
        attachLinkFieCnName.push(this.tempdata.cnName);
        this.$set(this.assetStatementDataSource[idx], 'attachLinkField', attachFieldCnName.join(','));
        this.$set(this.assetStatementDataSource[idx], 'attachLinkCnField', attachLinkFieCnName.join(','));
      }
      this.tempdata = null;
    },
    // 指标参数表 拖拽接收数据
    DropHandler(targetData) {
      this[targetData].push({
          id: this.tempdata.id,
          relateTableCnName: this.tempdata.sourceTableCnName,
          relateTableName: this.tempdata.sourceTableName,
          relateLinkCnField: this.tempdata.cnName,
          relateLinkField: this.tempdata.enName,
      })
      this.tempdata = {}
    },
    // tabs切换
    tabsValueChange(e) {
      for(let item of this.dataStructureList) {
        if(item.tableId == e) {
          this.dataStructureData = item.field;
          break;
        }
      }
    },
    queryDataStructureConfig() {
      getAction(this.url.queryDataStructureConfig, { modelId: this.modelId }).then((res)=>{
        this.assetStatementDataSource = res.result || [];
      })
    },
    queryDataStructure() {
      getAction(this.url.queryDataStructure, { modelId: this.modelId }).then((res)=>{
        if(res.code == 200) {
          this.dataStructureList = res.result;
          if(res.result && res.result.length) {
            this.tabsValue = res.result[0].tableId;
            this.dataStructureData = res.result[0].field;
          }
        }
      })
    },
    backModel() {
      let that = this;
      that.$confirm({
        title: '确认取消数据?',
        onOk() {
          that.$router.push(`/zdypzbb?id=${that.modelId}`);
        },
      });
    },
    saveData() {
      const config = this.assetStatementDataSource.map(item => {
        return {
          attachLinkField: item.attachLinkField,
          attachLinkCnField: item.attachLinkCnField,
          attachTableName: item.attachTableName,
          attachTableCnName: item.attachTableCnName,
          modelId: this.modelId,
          relateLinkField: item.relateLinkField,
          relateLinkCnField: item.relateLinkCnField,
          relateTableName: item.relateTableName,
          relateTableCnName: item.relateTableCnName,
        }
      })
      let params = {
        config: config,
        modelId: this.modelId,
      }
      postAction(this.url.saveDataStructure, params).then((res)=>{
        if(res.code == 200) {
          this.$message.success('保存成功');
          this.$router.push(`/zdypzbb?id=${this.modelId}`);
        }else {
          this.$message.error(res.message);
        }
      })
    },
  }
}
</script>

<style lang="less" scoped>
.dataStructureDragBtn {
  cursor: pointer;
  border: 1px solid #eeeeee;
  border-radius: 8px;
  padding: 4px 8px;
}
.contentCBtnBox {
  margin: 20px 0 10px;
  text-align: center;
}
.contentCBtn {
  cursor: pointer;
  margin-right: 15px;
  display: inline-block;
  border-radius: 5px;
  padding: 8px 20px;
  font-size: 14px;
  color: #FFFFFF;
  font-family: 'Arial Normal', 'Arial', sans-serif;
  font-weight: 400;
  font-style: normal;
  letter-spacing: normal;
  text-align: center;
  line-height: normal;
  &:last-child {
    margin-right: 0;
  }
}
.contentCSaveBtn {
  background-color: #3154A4;
}
.contentCShowBtn {
  background-color: #E1E3E4;
  color: #333333;
}
</style>